<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
require_once ('./application/controllers/authenticate.php');

class Disease extends Authenticate {

    const disease_PER_PAGE = 20;
    const disease_PAGE_RANGE = 5;

    function __construct() {
        global $active_system_function;
        $active_system_function = 'admin/medical/disease/index';
        parent::__construct();
        $this->load->model('medical_disease_model');
        $this->load->model('medical_parts_model');
        $this->load->model('medical_department_model');
        $this->load->model('medical_symptoms_model');
        $this->load->model('medical_object_model');
        $this->load->model('cms_tag_model');
        $this->load->model('cms_category_model');
        $this->load->model('admin_model');
        $this->load->model('cms_article_model');
        $this->load->library('upload');
    }

    protected function _eventLoadLayout() {
        $this->page['title'] = 'Quản lý bệnh';
        $this->module['title'] = 'Quản lý bệnh';
    }

    function index() {
        try {
            global $active_system_function;
            $active_system_function = 'admin/medical/disease/index';
            $this->filtered_list('index');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    private function check_has_privileges($data = array()) {
        $data['has_privilege_view'] = false;
        $data['has_privilege_new'] = false;
        $data['has_privilege_edit'] = false;
        $data['has_privilege_delete'] = false;
        if ($this->admin_model->is_admin()) {
            $data['has_privilege_view'] = true;
            $data['has_privilege_new'] = true;
            $data['has_privilege_edit'] = true;
            $data['has_privilege_delete'] = true;
        } else {
            $privileges = $this->admin_model->get_privileges();
            if (isset($privileges['admin/medical/disease/view'])) {
                $data['has_privilege_view'] = true;
            }
            if (isset($privileges['admin/medical/disease/new'])) {
                $data['has_privilege_new'] = true;
            }
            if (isset($privileges['admin/medical/disease/edit'])) {
                $data['has_privilege_edit'] = true;
            }
            if (isset($privileges['admin/medical/disease/delete'])) {
                $data['has_privilege_delete'] = true;
            }
        }
        return $data;
    }

    protected function _initData($return_url, $data = array()) {
        $filters = $this->input->post('filters');
        $current_page = intval($this->input->post('current_page'));
        $record_per_page = intval($this->input->post('record_per_page'));
        if ($record_per_page == 0) {
            $record_per_page = self::disease_PER_PAGE;
        }
        $conds = null;

        if (!empty($filters['id'])) {
            $conds['id'] = 'id =' . $filters['id'];
        }

        if (!empty($filters['name'])) {
            $conds['name'] = 'name LIKE "%' . $filters['name'] . '%"';
        }

        if(isset($filters['parts_id']) && (int)$filters['parts_id'] > 0){
            $conds['parts_id'] = 'parts_id = ' . $filters['parts_id'];
        }

        if(isset($filters['is_hidden']) && (int)$filters['is_hidden'] > 0){
            $conds['is_hidden'] = 'is_hidden = ' . $filters['is_hidden'];
        }

        //Đoạn này check filter của lọc data trong thêm bệnh
        if(isset($filters['disease']['id']) && $filters['disease']['id']){
            $conds['id'] = 'id =' . $filters['disease']['id'];
        }

        if(isset($filters['disease']['name']) && $filters['disease']['name']){
            $conds['name'] = 'name LIKE "%' .  $filters['disease']['name'] . '%"';
        }

        if(isset($filters['disease']['object']) && (int)$filters['disease']['object'] > 0){
            $conds['object_ids'] = ' CONCAT(",",object_ids,",") LIKE "%' .  $filters['disease']['object'] . '%"';
        }

        if(isset($filters['disease']['department']) && $filters['disease']['department']){
            $conds['department_id'] = 'department_id =' . $filters['disease']['department'];
        }

        if(isset($filters['disease']['season']) && (int)$filters['disease']['season'] > 0){
            $conds['season_ids'] = ' CONCAT(",",season_ids,",") LIKE "%' .  $filters['disease']['season'] . '%"';
        }

        if(isset($filters['disease']['is_top']) && (int)$filters['disease']['is_top'] > 0){
            $conds['is_top'] = ' is_top = ' .  $filters['disease']['is_top'];
        }
        //End check filter của lọc data trong thêm bệnh


        if (count($conds) == 0) {
            $query = 'SELECT COUNT(id) as count_result FROM medical_disease LIMIT 0, 1';
        } else {
            $query = 'SELECT COUNT(id) as count_result FROM medical_disease WHERE ' . implode(' AND ', $conds) . ' LIMIT 0, 1';
        }

        // Get Count disease
        $rs = $this->medical_disease_model->db->query($query);
        $count_results = $rs->row()->count_result;
        $rs->free_result();

        // Paginate
        if ($current_page <= 1) {
            $current_page = 1;
        }
        $start = ($current_page - 1) * $record_per_page;
        if ($start <= 0) {
            $start = 0;
        }
        $total_pages = ceil($count_results / $record_per_page);
        $delta = ceil(self::disease_PAGE_RANGE / 2);
        if ($current_page - $delta > $total_pages - self::disease_PAGE_RANGE) {
            $pag['lower'] = $total_pages - self::disease_PAGE_RANGE;
            $pag['upper'] = $total_pages;
        } else {
            if ($current_page - $delta < 0) {
                $delta = $current_page;
            }
            $offset = $current_page - $delta;
            $pag['lower'] = $offset + 1;
            $pag['upper'] = $offset + self::disease_PAGE_RANGE;
        }
        if ($pag['lower'] <= 1) {
            $pag['lower'] = 1;
        }
        if ($pag['upper'] >= $total_pages) {
            $pag['upper'] = $total_pages;
        }
        $pag['total'] = $total_pages;

        // Transfer Variables
        $data['return_url'] = $return_url;
        $data['record_per_page'] = $record_per_page;
        $data['count_total']  = $count_results;
        $data['current_page'] = $current_page;
        $data['paginator']    = $pag;
        $data['filters']      = $filters;
        $data['collection']   = $this->medical_disease_model->get_collection($start, $record_per_page, $conds, ' id DESC');
        $data['save_action']  = site_url('admin/medical/disease/save', true);
        return $data;
    }

    public function filtered_list($alias) {
        try {
            $privileges = $this->check_has_privileges();
            $ajax_action = $this->input->getParam('ajax_action');
            $data = $this->_initData($alias, $privileges);
            $data['form_action'] = site_url('admin/medical/disease/filtered_list/'.$alias , true);
            $data['season']      = $this->season;//lấy danh sách các mùa cấu hình trong controller
            $data['department']  = $this->medical_department_model->get_department();
            $data['list_object'] = $this->medical_object_model->get_list_object();//get all object
            if (empty($ajax_action)) {
                $this->setPageContent('admin/medical/disease/grid', $data);
                $this->renderLayout('layouts/fullcolumn');
            } else {
                $this->setPageContent('admin/medical/disease/ajax/list', $data);
                $this->renderLayout('layouts/ajax');
            }

        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    public function disease_relate($alias = 'publish'){
        try {
            $privileges = $this->check_has_privileges();
            $data       = $this->_initData($alias, $privileges);

            $data['season']      = $this->season;//lấy danh sách các mùa cấu hình trong controller
            $data['department']  = $this->medical_department_model->get_department();
            $data['list_object'] = $this->medical_object_model->get_list_object();//get all object

            $this->setPageContent('admin/medical/disease/ajax/disease_relate', $data);
            $this->renderLayout('layouts/ajax');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    function upload_multi(){
        // Config Upload
        $updated_time = time();
        $config['allowed_types'] = 'gif|jpg|png|bmp|psd';
        $config['max_size'] = '2000';
        $config['upload_path'] = './media/uploaded/' . date('Y', $updated_time) . '/' . date('m', $updated_time) . '/' . date('d', $updated_time) . '/';
        if (!file_exists($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }

        $data['mess'] = 'error';

        if (isset($_FILES['file']) && $_FILES['file']['name']) {
            $file_name  = $_FILES['file']['name'];
            $file_ext   = $this->getExtension($file_name);
            if($file_ext=='.gif'){
                $file_ext='.jpg';
            }

            if (in_array(strtolower($file_ext), array('.jpg', '.jpeg', '.gif', '.png'))) {
                if (!$_FILES['file']['error']) {
                    $this->upload->initialize($config);
                    $this->upload->do_upload('file');
                    // Render Image Path
                    $data_upload = $this->upload->data();
                    $image_path = $config['upload_path'] . $data_upload['file_name'];

                    if (strlen($data_upload['file_name']) > 0) {
                        $data['image']     = $image_path;
                        $data['image_url'] = render_src($image_path);
                        $data['mess']      = 'success';
                    }
                } elseif ($_FILES['Filedata']['error'] == 1) {
                    header('HTTP/1.0 408 Request Timeout');
                }
            } else {
                header('HTTP/1.0 408 Request Timeout');
            }
        } else {
            header('HTTP/1.0 408 Request Timeout');
        }

        echo json_encode($data);
        die();
    }

    function save() {
        try {
            $id = $this->input->post('id');
            $data = $this->input->post('data');

            $set_img_url = $this->input->post('set_img_url');
            $img_path    = $this->input->post('img_path');
            $updated_time = time();

            //-------------------Xử lý video đầu vào
            if(isset($data['video']) && $data['video']){
                $temp_video = array();
                $index      = 0;
                foreach($data['video'] as $k => $v){
                    if(isset($v['embed']) && $v['embed']){
                        $index++;
                        $temp_video[$index] = $v;
                    }
                }
            }else{
                unset($data['video']);
            }

            if(isset($temp_video)){
                $data['video'] = json_encode($temp_video);
            }

            //---------------image other
            if(isset($data['other_image']) && $data['other_image']){
                $temp_image = array();
                $index      = 0;
                foreach($data['other_image'] as $k => $v){
                    $index++;
                    $temp_image[$index] = $v;
                    if(isset($v['is_original'])){//set làm ảnh chính
                        $original_image = $v['image'];
                    }
                }
            }else{
                unset($data['other_image']);
            }

            if(isset($temp_image)){
                $data['other_image'] = json_encode($temp_image);
            }
            //--------------------End image other

            // Config Upload
            $config['allowed_types'] = 'gif|jpg|png|bmp|psd';
            $config['max_size'] = '500';
            $config['upload_path'] = './media/uploaded/' . date('Y', $updated_time) . '/' . date('m', $updated_time) . '/' . date('d', $updated_time) . '/';
            if (!file_exists($config['upload_path'])) {
                mkdir($config['upload_path'], 0777, true);
            }

            //-----------------------Xử lý dữ liệu đầu vào

            $object_ids = $this->input->post('object_ids');//lấy đối tượng trả về
            $season_ids = $this->input->post('season_ids');//lấy mùa trả về
            $tag_id     = $this->input->post('tag_id');//tag liên quan

            $data['object_ids'] = implode(',', $object_ids);
            $data['season_ids'] = implode(',', $season_ids);
            $data['tag_ids']    = implode(',', $tag_id);

            if(isset($data['symptoms_ids']) && $data['symptoms_ids']){
                $data['symptoms_ids'] = implode(',', $data['symptoms_ids']);//triệu chứng lâm sàng liên quan
            }else{
                $data['symptoms_ids'] = '';
            }

            if(isset($data['disease_ids']) && $data['disease_ids']){
                $data['disease_ids']  = implode(',', $data['disease_ids']);//bệnh liên quan
            }else{
                $data['disease_ids']  = '';
            }

            if(isset($data['category_article_ids']) && $data['category_article_ids']){
                $cat_article = array();
                foreach($data['category_article_ids'] as $val_cat){//nhóm danh mục và tin tức liên quan
                    $group = explode('_', $val_cat); //data này dc lưu theo dạng articleId_catId (phân biệt nhau bởi dấu ' _ ' )
                    if(isset($group[1]) && $group[1]){ //check danh mục phải có thì mới thêm tin tức (tin tức phải thuộc danh mục)
                        $cat_article[$group[0]] = array('article_id' => $group[0], 'cat_id' => $group[1]);
                        $data['list_article'][$group[0]] = $group[0];
                    }
                }

                $data['category_article_ids'] = json_encode($cat_article);
            }else{
                $data['category_article_ids'] = '';
            }
            //-----------------------End xử lý dữ liệu đầu vào

            if (empty($id)) {
                if (isset($_FILES['data_image']) && $_FILES['data_image']['size'] > 0) {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['image'] = $img_path;
                        }
                    } else {
                        $this->upload->initialize($config);
                        $this->upload->do_upload('data_image');
                        // Render Image Path
                        $data_upload = $this->upload->data();
                        $image_path = $config['upload_path'] . $data_upload['file_name'];
                        if (strlen($data_upload['file_name']) > 0) {
                            $data['image'] = $image_path;
                        }
                    }
                } else {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['image'] = $img_path;
                        }
                    }
                }

                if(isset($original_image) && $original_image){
                    $data['image'] = $original_image;
                }

                $privileges = $this->check_has_privileges();
                if (!$privileges['has_privilege_new']) {
                    $this->st_registry->register('admin/medical/disease/error', 'Bạn không có quyền tạo bệnh mới');
                    redirect(site_url('admin/medical/disease/index', true));
                    exit();
                }

                $data['created_date'] = time();
                $data['user_id'] = $this->admin_model->get_id();
                //$data['user_id']      =
                $id = $this->medical_disease_model->add_disease($data);
                $this->st_registry->register('admin/medical/disease/success', 'Thêm bệnh thành công');
            } else {
                $privileges = $this->check_has_privileges();
                if (!$privileges['has_privilege_edit']) {
                    $this->st_registry->register('admin/medical/disease/error', 'Bạn không có quyền sửa bệnh này');
                    redirect(site_url('admin/medical/disease/index', true));
                    exit();
                }

                $disease = $this->medical_disease_model->load_by_id($id);

                if (isset($_FILES['data_image']) && $_FILES['data_image']['size'] > 0) {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['image'] = $img_path;
                        }
                    } else {
                        $this->upload->initialize($config);
                        $this->upload->do_upload('data_image');
                        // Render Image Path
                        $data_upload = $this->upload->data();
                        $image_path = $config['upload_path'] . $data_upload['file_name'];
                        if (strlen($data_upload['file_name']) > 0) {
                            $data['image'] = $image_path;
                        }
                    }
                } else {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['image'] = $img_path;
                        }
                    }
                }

                if(isset($original_image) && $original_image){
                    $data['image'] = $original_image;
                }

                if (!isset($data['image'])) {
                    $data['image'] = $disease->image;
                }

                $data['created_date'] = time();
                $data['user_id']      = $this->admin_model->get_id();
                $this->medical_disease_model->update_disease($id, $data);
                $this->st_registry->register('admin/medical/disease/success', 'Sửa thông tin bệnh thành công');
            }
        } catch (Exception $ex) {
            $this->st_registry->register('admin/medical/disease/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
        redirect(site_url('admin/medical/disease/index', true));
    }

    function edit() {
        try {
            global $active_disease_function;
            $active_disease_function = 'admin/medical/disease/index';
            $data = $this->check_has_privileges();
            $id   = $this->input->getParam('id');

            $data['season']  = $this->season;//lấy danh sách các mùa cấu hình trong controller
            $data['disease']    = $this->medical_disease_model->load_by_id($id);
            $data['save_action'] = site_url('admin/medical/disease/save', true);

            if(get_field($data['disease'], 'season_ids')){//danh sách season_id dùng để check khi edit
                $arr_sea_ids = explode(',', get_field($data['disease'], 'season_ids'));
                $season_ids = array();
                foreach($arr_sea_ids as $val){
                    $season_ids[$val] = $val;
                }
            }

            if(get_field($data['disease'], 'tag_ids')){//danh sách tag_id dùng để check khi edit
                $arr_tag_ids = explode(',', get_field($data['disease'], 'tag_ids'));
                $tag_ids = array();
                foreach($arr_tag_ids as $val){
                    $tag_ids[$val] = $val;
                }
            }

            if(get_field($data['disease'], 'object_ids')){//danh sách object_ids dùng để check khi edit
                $arr_obj_ids = explode(',', get_field($data['disease'], 'object_ids'));
                $obj_ids = array();
                foreach($arr_obj_ids as $val){
                    $obj_ids[$val] = $val;
                }
            }

            if(get_field($data['disease'], 'video')){//danh sách video dùng để check khi edit
                $data['videos'] = json_decode(get_field($data['disease'], 'video'), true);
            }

            if(get_field($data['disease'], 'other_image')){//danh sách image other dùng để check khi edit
                $data['other_image'] = json_decode(get_field($data['disease'], 'other_image'), true);
            }

            if(get_field($data['disease'], 'symptoms_ids')){//danh sách object_ids dùng để check khi edit
                $arr_symptoms_ids = explode(',', get_field($data['disease'], 'symptoms_ids'));
                $symptoms_ids = array();
                foreach($arr_symptoms_ids as $val){
                    $symptoms_ids[$val] = $this->medical_symptoms_model->load_by_id($val);
                }
                $data['symptoms_ids'] = $symptoms_ids;
            }

            if(get_field($data['disease'], 'disease_ids')){//danh sách disease_ids dùng để check khi edit
                $arr_disease_ids = explode(',', get_field($data['disease'], 'disease_ids'));
                $disease_ids = array();
                foreach($arr_disease_ids as $val){
                    $disease_ids[$val] = $this->medical_disease_model->load_by_id($val);
                }
                $data['disease_ids'] = $disease_ids;
            }

            if(get_field($data['disease'], 'category_article_ids')){//danh sách category_article_ids dùng để check khi edit
                $temp_group = json_decode(get_field($data['disease'], 'category_article_ids'), true);
                $list_group = array();
                foreach($temp_group as $val_g){
                    $val_g['article_detail'] = $this->cms_article_model->load_by_id($val_g['article_id']);
                    $list_group[$val_g['article_id']] = $val_g;
                }

                $data['list_group_edit'] = $list_group;
            }

            $data['department'] = $this->medical_department_model->get_department();
            $data['season_ids'] = isset($season_ids) ? $season_ids : 0;

            $data['list_tag']   = $this->cms_tag_model->get_tags();//get all tag
            $data['tag_ids']    = isset($tag_ids) ? $tag_ids : 0;

            $data['list_object'] = $this->medical_object_model->get_list_object();//get all object
            $data['obj_ids']     = isset($obj_ids) ? $obj_ids : 0;

            $data['users'] = $this->admin_model->get_list();//lấy user đăng article
            $data['categories'] = $this->cms_category_model->get_list();//lấy danh mục hệ thống để tìm tin đăng article

            $data['list_parts']  = json_encode($this->medical_parts_model->get_list());//lấy danh sách bộ phận cơ thể

            $data['category_relate'] = $this->cms_category_model->get_group_cat();//lấy danh mục liên quan (ko lấy hệ thống) để check tin tức liên quan
            $this->setPageContent('admin/medical/disease/edit', $data);
            $this->renderLayout('layouts/fullcolumn');
        } catch (Exception $ex) {
            $this->st_registry->register('admin/medical/disease/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
    }

    function delete() {
        try {
            $privileges = $this->check_has_privileges();
            $id = intval(trim($this->input->getParam('id')));
            if (empty($id)) {
                $this->st_registry->register('admin/medical/disease/error', 'Không xác định được bệnh cần xóa (ID)?');
                redirect(site_url('admin/medical/disease/index', true));
                exit();
            }
            if (!$privileges['has_privilege_delete']) {
                $this->st_registry->register('admin/medical/disease/error', 'Bạn không có quyền xóa bệnh này');
                redirect(site_url('admin/medical/disease/index', true));
                exit();
            }
            $this->medical_disease_model->delete_disease($id);
            $this->st_registry->register('admin/medical/disease/success', 'Xóa bệnh thành công');
        } catch (Exception $ex) {
            $this->st_registry->register('admin/medical/disease/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
        redirect(site_url('admin/medical/disease/index', true));
    }

    function getExtension($file) {
        $pos = strrpos($file, '.');
        if (!$pos) {
            return FALSE;
        }
        $str = substr($file, $pos, strlen($file));
        return strtolower($str);
    }
}